
/**
 * Copyright 2009 cestum.org
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
 
package org.waveprotocol.wave.model.document.operation.algorithm {
import mx.collections.ArrayCollection;

import org.goverla.collections.HashMap;
import org.waveprotocol.wave.model.document.operation.AttributesUpdate;
import org.waveprotocol.wave.model.document.operation.BufferedDocOp;
import org.waveprotocol.wave.model.document.operation.EvaluatingDocOpCursor;
import org.waveprotocol.wave.model.document.operation.algorithm.target.AnnotationQueue;
import org.waveprotocol.wave.model.document.operation.algorithm.target.ComposeError;
import org.waveprotocol.wave.model.document.operation.algorithm.target.DefaultPreTarget;
import org.waveprotocol.wave.model.document.operation.algorithm.target.FinisherPostTarget;
import org.waveprotocol.wave.model.document.operation.algorithm.target.PostAnnotationQueue;
import org.waveprotocol.wave.model.document.operation.algorithm.target.PreAnnotationQueue;
import org.waveprotocol.wave.model.document.operation.algorithm.target.Target;
import org.waveprotocol.wave.model.document.operation.impl.AttributesUpdateImpl;
import org.waveprotocol.wave.model.document.operation.impl.DocOpBuffer;
import org.waveprotocol.wave.model.document.operation.impl.DocumentOperationUtil;

/**
 * A utility class for composing document operations.
 *
 * TODO: Make detection of illegal compositions more thorough.
 */
public final class Composer {
	/**
   * The currently active annotations in the first operation. This maps keys to
   * pairs representing the old annotation value and the new annotation value.
   */
  public var preAnnotations:HashMap=  new HashMap();

  /**
   * The currently active annotations in the second operation. This maps keys to
   * pairs representing the old annotation value and the new annotation value.
   */
  public var postAnnotations:HashMap=  new HashMap();

  public var preAnnotationQueue:AnnotationQueue;

  public  var postAnnotationQueue:AnnotationQueue;

  public var normalizer:EvaluatingDocOpCursor=
      OperationNormalizer.createNormalizer(new DocOpBuffer());

  public var defaultTarget:Target;

  public var target:Target;

  function Composer() {
	  preAnnotationQueue = new PreAnnotationQueue(this);
	  postAnnotationQueue = new PostAnnotationQueue(this);
	  defaultTarget = new DefaultPreTarget(this);
  }

  private function composeOperations(op1:BufferedDocOp, op2:BufferedDocOp):BufferedDocOp {
    target = defaultTarget;
    var op1Index:int= 0;
    var op2Index:int= 0;
    while (op1Index < op1.size()) {
      op1.applyComponent(op1Index++, target);
      while (target.isPostTarget()) {
		  if (op2Index >= op2.size()) {
			  //More solid Error
			  throw new Error("Document size mismatch: "
				  + "op1 resulting length=" + DocumentOperationUtil.resultingDocumentLength(op1)
				  + ", op2 initial length=" + DocumentOperationUtil.initialDocumentLength(op2));
		  }
        op2.applyComponent(op2Index++, target);
      }
    }
    if (op2Index < op2.size()) {
      target = new FinisherPostTarget(this);
      while (op2Index < op2.size()) {
        op2.applyComponent(op2Index++, target);
      }
    }
    flushAnnotations();
    return BufferedDocOp(normalizer.finish());
  }

	//For overloaded add methods
	 public static function compose(op1:BufferedDocOp, op2:BufferedDocOp) { 
	     Composer["compose"+arguments.length].apply(arguments);  
	}  
  /**
   * Perform a composition of two operations.
   *
   * @param op1 the first operation
   * @param op2 the second operation
   * @return the result of the composition
   * @throws OperationException if there was a problem composing
   */
  public static function compose2(op1:BufferedDocOp, op2:BufferedDocOp):BufferedDocOp {
    try {
      return new Composer().composeOperations(op1, op2);
    } catch (e:ComposeError) {
      //throw new OperationException(e.getMessage());
		throw new Error(e.getMessage());
    }
	return null;
  }

  /**
   * Compose operations.
   *
   * TODO: Rewrite to have proper exceptions-throwing.
   *
   * @param operations an iterator through the operations to compose
   * @return the result of the composition
   */
  public static function compose1(operations:ArrayCollection):BufferedDocOp {
    var collector:DocOpCollector= new DocOpCollector();
    for(var i:int =0; i< operations.length; i++) {
	  var operation:BufferedDocOp = BufferedDocOp(operations.getItemAt(i));
      collector.add(operation);
    }
    return collector.composeAll();
  }

  public function flushAnnotations():void {
    preAnnotationQueue.flush();
    postAnnotationQueue.flush();
  }

  public static function invertUpdate(attrUpdate:AttributesUpdate):AttributesUpdate {
    var inverseUpdate:AttributesUpdate= new AttributesUpdateImpl(null);
    // TODO: This is a little silly. We should do this a better way.
    for (var i:int= 0; i < attrUpdate.changeSize(); ++i) {
      inverseUpdate = inverseUpdate.composeWith(AttributesUpdateImpl.of(
          attrUpdate.getChangeKey(i), attrUpdate.getNewValue(i), attrUpdate.getOldValue(i)));
    }
    return inverseUpdate;
  }

}
}